/*
	The Sentinel by Copy112 & Bekka
*/

AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')

ENT.LastMove = 0 -- Dont change this
ENT.target = nil
ENT.MoveDelay = 0.01 -- Change to set how often the sentinel should rotate

function ENT:Initialize()
	self:SetModel("models/props_junk/wood_crate001a.mdl")
	self:PhysicsInit(SOLID_VPHYSICS)
	self:SetMoveType(MOVETYPE_VPHYSICS)
	self:SetSolid(SOLID_VPHYSICS)
	self:StartMotionController()
	
	-- Yes a melon head, what else?
	self.head = ents.Create("prop_physics")
	self.head:SetModel( "models/props_junk/watermelon01.mdl" )
	self.head:SetPos(self:GetPos() + Vector(0,0,30))
	self.head:PhysicsInit( SOLID_VPHYSICS )
	self.head:SetMoveType( MOVETYPE_VPHYSICS )
	self.head:SetSolid( SOLID_VPHYSICS )
	self.head:SetParent(self.Entity)
	self.head:Spawn()
	
	self:SetNWEntity("head", self.head)
    
	local phys = self:GetPhysicsObject()
	
	-- Lets freeze the sentinel, so he wont move around, how would that look?
	if phys:IsValid() then
		phys:EnableMotion(false)
		phys:Sleep()
	end
end

-- Todo write rotate script and laser tracking thing that will kill you :D
function ENT:Think()
	--print(self.LastMove) -- Debug
	-- Rotate the sentinel
	if self.LastMove + self.MoveDelay <= CurTime() and !self.target then
	
		self:SetAngles(self:GetAngles() + Angle(0,0.05,0))
		
		self.LastMove = CurTime()
		
	end
	
	self.target = nil
	
	-- Check if we finds a player
	local tracedata = {}
	tracedata.start = self.head:GetPos()
	tracedata.endpos = self.head:GetPos() + (self.head:GetForward() * 500) + (self.head:GetUp())
	tracedata.filter = self
	local trace = util.TraceLine(tracedata)
	if trace.HitNonWorld then
		target = trace.Entity
		-- Make sure its a player
		if target:IsPlayer() then
			--target:Kill()
			print("PLAYER FOUND")
			self.target = target
		end
	
	end
	
	-- Handle the sentinel changing color when finding someone
	if self.target then
		self:SetColor(255, 0, 0, 255)
		self.head:SetColor(255, 0, 0, 255)
	else
		self:SetColor(255, 255, 255, 255)
		self.head:SetColor(255, 255, 255, 255)
	end
	
	-- Think every 0.1s
	self:NextThink(CurTime() + 0.01)
	
	return true
end
